package com.ethink.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ethink.framework.common.db.PageUtils;
import com.ethink.framework.common.exception.BusinessException;
import com.ethink.id.generator.IdGenerator;
import com.ethink.order.api.constant.OrderRespCode;
import com.ethink.order.api.enums.SaleDemandDetailOrderStatusEnum;
import com.ethink.order.api.enums.SaleDemandOrderOrderStatusEnum;
import com.ethink.order.api.info.SaleDemandOrderDetailInfo;
import com.ethink.order.api.info.SaleDemandOrderInfo;
import com.ethink.order.api.info.SaleDemandOrderModeInfo;
import com.ethink.order.api.model.PreSuppleOrderDetailModel;
import com.ethink.order.api.request.*;
import com.ethink.order.api.response.SaleDemandOrderAddResponse;
import com.ethink.order.api.response.SaleDemandOrderDeleteResponse;
import com.ethink.order.api.response.SaleDemandOrderDetailResponse;
import com.ethink.order.common.entity.SaleDemandOrder;
import com.ethink.order.common.entity.SaleDemandOrderDetail;
import com.ethink.order.common.mapper.SaleDemandOrderDetailMapper;
import com.ethink.order.common.mapper.SaleDemandOrderMapper;
import com.ethink.order.converter.SaleDemandOrderConverter;
import com.ethink.order.manager.SaleChannelRequestManager;
import com.ethink.order.service.PurchaseOrderDetailService;
import com.ethink.order.service.SaleDemandOrderDetailService;
import com.ethink.order.service.SaleDemandOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 销售需求单 Service接口实现
 *
 * @author default
 * @date 2022-10-31
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class SaleDemandOrderServiceImpl implements SaleDemandOrderService {

    @Autowired
    private SaleDemandOrderMapper saleDemandOrderMapper;

    @Autowired
    private SaleDemandOrderDetailMapper saleDemandOrderDetailMapper;

    @Autowired
    @Lazy
    private SaleDemandOrderDetailService saleDemandOrderDetailService;

    @Autowired
    private SaleDemandOrderConverter saleDemandOrderConverter;

    @Autowired
    private IdGenerator idGenerator;

    @Override
    public Page<SaleDemandOrderInfo> querySaleDemandOrder(SaleDemandOrderQueryRequest request) {
        SaleChannelRequestManager.fill(request, 0, 1, 2);
        return saleDemandOrderMapper.querySaleDemandOrder(PageUtils.buildPage(request), request);
    }

    @Override
    public SaleDemandOrderDetailResponse getSaleDemandOrderByNo(String orderNo) {
        SaleDemandOrderDetailResponse response = new SaleDemandOrderDetailResponse();
        List<SaleDemandOrderDetailInfo> item = saleDemandOrderMapper.getSaleDemandOrderByNo(orderNo);
        response.setItem(item);
        SaleDemandOrder saleDemandOrder = saleDemandOrderMapper.selectOne(new LambdaQueryWrapper<SaleDemandOrder>()
                .eq(SaleDemandOrder::getOrderNo, orderNo));
        SaleDemandOrderInfo saleDemandOrderInfo = saleDemandOrderConverter.convertFrom(saleDemandOrder);
        response.setSaleDemandOrderInfo(saleDemandOrderInfo);
        return response;
    }

    @Override
    public List<SaleDemandOrderInfo> listSaleDemandOrder(SaleDemandOrderQueryRequest request) {
        return saleDemandOrderMapper.listSaleDemandOrder(request);
    }

    @Override
    public SaleDemandOrderAddResponse addSaleDemandOrder(SaleDemandOrderAddRequest request) {
        String orderNo = idGenerator.xq();
        request.setOrderNo(orderNo);
        SaleDemandOrderAddResponse response = new SaleDemandOrderAddResponse();
        SaleDemandOrder saleDemandOrder = new SaleDemandOrder();
        BeanUtils.copyProperties(request, saleDemandOrder, "item");
        if (StringUtils.isBlank(request.getSaleSubChannel())) {
            saleDemandOrder.setSaleSubChannel("Z000");
        }
        //计算预计销售价不含税-本币
        saleDemandOrderMapper.insert(saleDemandOrder);
        //保存商品信息
        saleDemandOrderDetailService.batchInsert(request.getItem(), orderNo, request.getExchangeRate(), request.getDefaultTaxRate());
        response.setOrderNo(orderNo);
        return response;
    }

    @Override
    public SaleDemandOrderDeleteResponse deleteSaleDemandOrder(Long saleDemandOrderId) {
        SaleDemandOrderDeleteResponse response = new SaleDemandOrderDeleteResponse();
        SaleDemandOrder saleDemandOrder = saleDemandOrderMapper.selectById(saleDemandOrderId);
        //如果状态 = 1 执行删除逻辑
        if (SaleDemandOrderOrderStatusEnum.S1.getIntValue().equals(saleDemandOrder.getOrderStatus())) {
            saleDemandOrder.setIsDeleted(true);
            saleDemandOrderMapper.updateById(saleDemandOrder);
            LambdaUpdateWrapper<SaleDemandOrderDetail> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SaleDemandOrderDetail::getOrderNo, saleDemandOrder.getOrderNo());
            updateWrapper.set(SaleDemandOrderDetail::getIsDeleted, true);
            saleDemandOrderDetailMapper.update(null, updateWrapper);
        } else {
            saleDemandOrder.setOrderStatus(SaleDemandOrderOrderStatusEnum.S1.getIntValue());
            saleDemandOrderMapper.updateById(saleDemandOrder);
        }
        return response;
    }

    @Override
    public void updateStatus(String orderNo, Integer status) {
        saleDemandOrderMapper.update(null, new LambdaUpdateWrapper<SaleDemandOrder>()
                .eq(SaleDemandOrder::getOrderNo, orderNo)
                .set(SaleDemandOrder::getOrderStatus, status));
    }

    @Override
    public SaleDemandOrderDetail oaPass(OAPassRequest request) {
        SaleDemandOrderDetail saleDemandOrderDetail = saleDemandOrderDetailMapper.selectById(request.getId());
        if (!SaleDemandDetailOrderStatusEnum.S2.getIntValue().equals(saleDemandOrderDetail.getDetailOrderStatus())) {
            throw new BusinessException(OrderRespCode.ORDER_STATUS_IS_NOT_LOCK);
        }
        saleDemandOrderDetailMapper.update(null, new LambdaUpdateWrapper<SaleDemandOrderDetail>()
                .eq(SaleDemandOrderDetail::getId, request.getId())
                .set(SaleDemandOrderDetail::getDetailOrderStatus, SaleDemandDetailOrderStatusEnum.S3.getIntValue())
        );
        //查询该需求下的商品是否都确认了采购
        List<SaleDemandOrderDetail> details = saleDemandOrderDetailMapper.selectList(new LambdaQueryWrapper<SaleDemandOrderDetail>()
                .eq(SaleDemandOrderDetail::getOrderNo, saleDemandOrderDetail.getOrderNo()));
        if (CollUtil.isNotEmpty(details)) {
            List<SaleDemandOrderDetail> collect = details.stream().filter(a -> !SaleDemandDetailOrderStatusEnum.S3.getIntValue().equals(a.getDetailOrderStatus()))
                    .collect(Collectors.toList());
            //修改订单状态为已完成
            if (collect.size() == 0) {
                updateStatus(saleDemandOrderDetail.getOrderNo(), SaleDemandOrderOrderStatusEnum.S4.getIntValue());
            }
        }
        return saleDemandOrderDetail;
    }

    @Override
    public Page<PreSuppleOrderDetailModel> pageQueryByPreSupple(PreSupplePageQueryRequest request) {
        SaleChannelRequestManager.fill(request, 0, 1, 2);
        return saleDemandOrderMapper.pageQueryByPreSupple(PageUtils.buildPage(request), request);
    }

    @Override
    public String update(SaleDemandOrderUpdateRequest request) {
        Integer count = saleDemandOrderMapper.selectCount(new LambdaQueryWrapper<SaleDemandOrder>()
                .eq(SaleDemandOrder::getId, request.getId())
                .eq(SaleDemandOrder::getOrderStatus, SaleDemandOrderOrderStatusEnum.S1.getIntValue()));
        if (count == 0) {
            throw new BusinessException(OrderRespCode.SALE_ORDER_DETAIL_STATUS_IS_NOT_MET);
        }
        SaleDemandOrder saleDemandOrder = saleDemandOrderMapper.selectById(request.getId());
        BeanUtil.copyProperties(request, saleDemandOrder, "item");
        saleDemandOrderDetailMapper.delete(new LambdaQueryWrapper<SaleDemandOrderDetail>()
                .eq(SaleDemandOrderDetail::getOrderNo, saleDemandOrder.getOrderNo())
        );
        if (CollUtil.isNotEmpty(request.getItem())) {
            saleDemandOrderDetailService.batchInsert(request.getItem(), saleDemandOrder.getOrderNo(), request.getExchangeRate(), request.getDefaultTaxRate());
        }
        saleDemandOrderMapper.updateById(saleDemandOrder);
        return saleDemandOrder.getOrderNo();
    }

    @Override
    public Integer updateRemark(SaleDemandUpdateRemarkRequest request) {
        return saleDemandOrderMapper.update(null, new LambdaUpdateWrapper<SaleDemandOrder>()
                .eq(SaleDemandOrder::getId, request.getId())
                .set(SaleDemandOrder::getPoOrderNo, request.getPoOrderNo())
                .set(SaleDemandOrder::getRemark, request.getRemark()));
    }

    @Override
    public SaleDemandOrderInfo queryMainByOrderNo(String orderNo) {
        SaleDemandOrder saleDemandOrder = saleDemandOrderMapper.selectOne(new LambdaQueryWrapper<SaleDemandOrder>()
                .eq(SaleDemandOrder::getOrderNo, orderNo));
        SaleDemandOrderInfo saleDemandOrderInfo = saleDemandOrderConverter.convertFrom(saleDemandOrder);
        return saleDemandOrderInfo;
    }

    /**
     * 货品模式分页查询
     *
     * @param request
     * @return
     */
    @Override
    public Page<SaleDemandOrderModeInfo> querySaleDemandOrderMode(SaleDemandOrderQueryModeRequest request) {
//        SaleChannelRequestManager.fill(request, 0, 1, 2);
        if (ObjectUtil.isNotEmpty(request.getSaleChannelArr())) {
            request.setSaleChannel(request.getSaleChannelArr()[0]);
            if (request.getSaleChannelArr().length > 1) {
                request.setSaleSubChannel(request.getSaleChannelArr()[1]);
            }
        }
        return saleDemandOrderMapper.querySaleDemandOrderMode(PageUtils.buildPage(request), request);
    }
}
